package com.ruoyi.veterinary.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.veterinary.mapper.VetPurchaseMapper;
import com.ruoyi.veterinary.domain.VetPurchase;
import com.ruoyi.veterinary.domain.VetInventory;
import com.ruoyi.veterinary.service.IVetPurchaseService;
import com.ruoyi.veterinary.service.IVetInventoryService;
import com.ruoyi.common.exception.ServiceException;

/**
 * 进货管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-19
 */
@Service
public class VetPurchaseServiceImpl implements IVetPurchaseService 
{
    @Autowired
    private VetPurchaseMapper vetPurchaseMapper;
    
    @Autowired
    private IVetInventoryService vetInventoryService;

    /**
     * 查询进货管理
     * 
     * @param purchaseId 进货管理主键
     * @return 进货管理
     */
    @Override
    public VetPurchase selectVetPurchaseByPurchaseId(Long purchaseId)
    {
        return vetPurchaseMapper.selectVetPurchaseByPurchaseId(purchaseId);
    }

    /**
     * 查询进货管理列表
     * 
     * @param vetPurchase 进货管理
     * @return 进货管理
     */
    @Override
    public List<VetPurchase> selectVetPurchaseList(VetPurchase vetPurchase)
    {
        return vetPurchaseMapper.selectVetPurchaseList(vetPurchase);
    }

    /**
     * 新增进货管理
     * 
     * @param vetPurchase 进货管理
     * @return 结果
     */
    @Override
    public int insertVetPurchase(VetPurchase vetPurchase)
    {
        // 生成采购单号
        if (vetPurchase.getPurchaseOrderNo() == null || vetPurchase.getPurchaseOrderNo().isEmpty()) {
            vetPurchase.setPurchaseOrderNo(generatePurchaseOrderNo());
        }
        
        // 计算总金额
        if (vetPurchase.getPurchasePrice() != null && vetPurchase.getQuantity() != null) {
            vetPurchase.setTotalAmount(vetPurchase.getPurchasePrice().multiply(
                java.math.BigDecimal.valueOf(vetPurchase.getQuantity())));
        }
        
        // 设置默认验收状态
        if (vetPurchase.getAcceptanceStatus() == null || vetPurchase.getAcceptanceStatus().isEmpty()) {
            vetPurchase.setAcceptanceStatus("待验收");
        }
        
        vetPurchase.setCreateTime(DateUtils.getNowDate());
        return vetPurchaseMapper.insertVetPurchase(vetPurchase);
    }

    /**
     * 修改进货管理
     * 
     * @param vetPurchase 进货管理
     * @return 结果
     */
    @Override
    public int updateVetPurchase(VetPurchase vetPurchase)
    {
        // 重新计算总金额
        if (vetPurchase.getPurchasePrice() != null && vetPurchase.getQuantity() != null) {
            vetPurchase.setTotalAmount(vetPurchase.getPurchasePrice().multiply(
                java.math.BigDecimal.valueOf(vetPurchase.getQuantity())));
        }
        
        vetPurchase.setUpdateTime(DateUtils.getNowDate());
        return vetPurchaseMapper.updateVetPurchase(vetPurchase);
    }

    /**
     * 批量删除进货管理
     * 
     * @param purchaseIds 需要删除的进货管理主键
     * @return 结果
     */
    @Override
    public int deleteVetPurchaseByPurchaseIds(Long[] purchaseIds)
    {
        return vetPurchaseMapper.deleteVetPurchaseByPurchaseIds(purchaseIds);
    }

    /**
     * 删除进货管理信息
     * 
     * @param purchaseId 进货管理主键
     * @return 结果
     */
    @Override
    public int deleteVetPurchaseByPurchaseId(Long purchaseId)
    {
        return vetPurchaseMapper.deleteVetPurchaseByPurchaseId(purchaseId);
    }

    /**
     * 生成采购单号
     * 
     * @return 采购单号
     */
    @Override
    public String generatePurchaseOrderNo()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        // 这里可以根据实际需求实现序号生成逻辑
        String sequence = String.format("%03d", (int)(Math.random() * 1000));
        return "CG" + dateStr + sequence;
    }

    /**
     * 查询待验收采购单列表
     * 
     * @return 待验收采购单集合
     */
    @Override
    public List<VetPurchase> selectPendingAcceptanceList()
    {
        VetPurchase queryParam = new VetPurchase();
        queryParam.setAcceptanceStatus("待验收");
        return vetPurchaseMapper.selectVetPurchaseList(queryParam);
    }

    /**
     * 验收入库操作
     * 
     * @param vetPurchase 采购信息
     * @return 结果
     */
    @Override
    @Transactional
    public int processAcceptance(VetPurchase vetPurchase)
    {
        try {
            // 重新查询完整的采购信息，确保获取到所有字段
            VetPurchase fullPurchaseInfo = vetPurchaseMapper.selectVetPurchaseByPurchaseId(vetPurchase.getPurchaseId());
            if (fullPurchaseInfo == null) {
                throw new ServiceException("采购记录不存在");
            }
            
            // 调试日志：显示查询到的完整信息
            System.out.println("查询到的完整采购信息 - ID: " + fullPurchaseInfo.getPurchaseId() + 
                ", 药品: " + fullPurchaseInfo.getDrugName() + 
                ", 数量: " + fullPurchaseInfo.getQuantity() + 
                ", 批号: " + fullPurchaseInfo.getBatchNumber());
            
            // 合并验收信息到完整记录中
            fullPurchaseInfo.setAcceptanceStatus(vetPurchase.getAcceptanceStatus());
            fullPurchaseInfo.setAcceptanceResult(vetPurchase.getAcceptanceResult());
            fullPurchaseInfo.setAcceptor(vetPurchase.getAcceptor());
            fullPurchaseInfo.setAcceptanceDate(DateUtils.getNowDate());
            
            // 处理批号逻辑 - 如果批号为空，生成或使用现有批号
            if (StringUtils.isEmpty(fullPurchaseInfo.getBatchNumber())) {
                // 查找相同药品的最新库存记录
                VetInventory latestInventory = vetInventoryService.selectLatestInventoryByDrug(
                    fullPurchaseInfo.getDrugName());
                
                if (latestInventory != null) {
                    // 如果有现有库存，使用相同批号进行累加
                    fullPurchaseInfo.setBatchNumber(latestInventory.getBatchNumber());
                } else {
                    // 如果没有现有库存，生成新批号
                    fullPurchaseInfo.setBatchNumber("BATCH" + DateUtils.dateTimeNow("yyyyMMdd") + 
                        String.format("%04d", fullPurchaseInfo.getPurchaseId()));
                }
            }
            
            // 更新验收信息
            int result = vetPurchaseMapper.updateVetPurchase(fullPurchaseInfo);
            
            // 如果验收通过，自动创建或更新库存
            if (result > 0 && "通过".equals(fullPurchaseInfo.getAcceptanceStatus())) {
                processInventoryUpdate(fullPurchaseInfo);
            }
            
            return result;
        } catch (Exception e) {
            throw new ServiceException("验收处理失败：" + e.getMessage());
        }
    }
    
    /**
     * 处理库存更新
     * 
     * @param vetPurchase 采购信息
     */
    private void processInventoryUpdate(VetPurchase vetPurchase) {
        try {
            // 确保数量不为null
            if (vetPurchase.getQuantity() == null || vetPurchase.getQuantity() <= 0) {
                throw new ServiceException("进货数量不能为空或小于等于0");
            }
            
            // 检查是否已存在相同药品和批号的库存
            VetInventory existingInventory = vetInventoryService.selectInventoryByDrugAndBatch(
                vetPurchase.getDrugName(), vetPurchase.getBatchNumber());
            
            if (existingInventory != null) {
                // 累加到现有库存
                System.out.println("找到现有库存，ID: " + existingInventory.getInventoryId() + 
                    ", 当前数量: " + existingInventory.getQuantity() + 
                    ", 要增加: " + vetPurchase.getQuantity());
                
                int updateResult = vetInventoryService.updateInventoryQuantity(
                    existingInventory.getInventoryId(), vetPurchase.getQuantity());
                
                System.out.println("库存更新结果: " + updateResult);
            } else {
                // 创建新的库存记录
                    VetInventory newInventory = new VetInventory();
                    newInventory.setDrugName(vetPurchase.getDrugName());
                    newInventory.setDrugSpecification(vetPurchase.getDrugSpecification() != null ? vetPurchase.getDrugSpecification() : "");
                    newInventory.setManufacturerId(vetPurchase.getManufacturerId());
                    newInventory.setBatchNumber(vetPurchase.getBatchNumber());
                    newInventory.setPurchasePrice(vetPurchase.getPurchasePrice());
                    newInventory.setQuantity(vetPurchase.getQuantity());
                    newInventory.setWithdrawalPeriod(vetPurchase.getWithdrawalPeriod());
                    newInventory.setExpiryDate(vetPurchase.getExpiryDate());
                    newInventory.setInventoryStatus("正常");
                    newInventory.setStorageCondition("常温");
                    newInventory.setApplicableAnimals("通用");
                    newInventory.setDiseaseType("常规治疗");
                    newInventory.setKeywords(vetPurchase.getDrugName() + " " + 
                        (vetPurchase.getDrugSpecification() != null ? vetPurchase.getDrugSpecification() : ""));
                    newInventory.setWarningQuantity(10); // 默认预警数量
                    
                    // 添加调试日志
                    System.out.println("创建新库存记录: " + vetPurchase.getDrugName() + ", 数量: " + vetPurchase.getQuantity());
                    
                    int insertResult = vetInventoryService.insertVetInventory(newInventory);
                    System.out.println("库存插入结果: " + insertResult);
            }
        } catch (Exception e) {
            throw new ServiceException("库存更新失败：" + e.getMessage());
        }
    }
}